package com.linkage.seapeak.activity.message;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProTalkActivity;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.seapeak.adapter.MsgMemberAdapter;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.CrediterNewUser;
import com.linkage.seapeak.pojo.CrediterUser;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 群发消息第一步，选择人员
 */
public class MultiSelectActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    List<CrediterNewUser> userList;
    AYSwipeRecyclerView recyclerView;
    MsgMemberAdapter adapter;

    TextView count_member, all_select, screen_member;
    TextView menu;

    String projectId;

    Integer committee;
    Boolean onlineStatus;
    Boolean kindTax;
    Boolean kindGuarantee;
    Boolean kindOther;
    Boolean kindOrdinary;
    Double minAmountDeclared;
    Double maxAmountDeclared;
    Double minConfirmAmount;
    Double maxConfirmAmount;
    String processStatus;

    int pageNo = 1;
    int pageSize = 100;
    String type = "0";

    //选择人员列表
    List<CrediterNewUser> selectList;
    //已选择人的ids;
    List<String> selectIds;
    List<String> alreadySelectIds;
    boolean canSelectAlready = true;

    String form = "";

    boolean isAll = false;

    /**
     * 开启页面
     * @param context
     * @param projectId
     */
    public static void start(Context context, String projectId){
        Intent intent = new Intent(context, MultiSelectActivity.class);
        intent.putExtra("projectId", projectId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_select, "选择成员");
        init();
    }

    private void init() {
        projectId = getIntent().getStringExtra("projectId");
        canSelectAlready = getIntent().getBooleanExtra("canSelectAlready", true);
        alreadySelectIds = getIntent().getStringArrayListExtra("alreadySelectIds");
        if (alreadySelectIds == null)
            alreadySelectIds = new ArrayList<>();
        selectIds = new ArrayList<>();
        selectIds.addAll(alreadySelectIds);

        try {
            type = getIntent().getStringExtra("type");
            form =  getIntent().getStringExtra("form");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (type == null)
            type = "0";

        recyclerView = findViewById(R.id.member_list);
        count_member = findViewById(R.id.count_member);
        all_select = findViewById(R.id.all_select);
        screen_member = findViewById(R.id.screen_member);

        userList = new ArrayList<>();
        selectList = new ArrayList<>();
        recyclerView.setOnRefreshLoadLister(this);
        recyclerView.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        adapter = new MsgMemberAdapter(MultiSelectActivity.this, userList, true);
        recyclerView.setAdapter(adapter);
        recyclerView.startLoadFirst();
        recyclerView.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                if (!canSelectAlready && alreadySelectIds.contains(userList.get(position).getCreditorid()))
                    return;

                boolean itemCheck = userList.get(position).isCheck;
                userList.get(position).isCheck = !itemCheck;
                if (!itemCheck) {
                    selectList.add(userList.get(position));
                    selectIds.add(userList.get(position).getCreditorid());
                } else {
                    for(int i = 0;i < selectList.size();i++) {
                        if (selectList.get(i).getSysUserId().equals(userList.get(position).getSysUserId())) {
                            selectList.remove(userList.get(position));
                            selectIds.remove(userList.get(position).getCreditorid());
                            break;
                        }
                    }
                }
                adapter.notifyDataSetChanged();
                if ("0".equalsIgnoreCase(type)) {
                    count_member.setText("共计："+selectList.size());
                    menu.setText("下一步(" + selectList.size() + ")");
                } else {
                    count_member.setText("共计："+selectList.size());
                    menu.setText("完成(" + selectList.size() + ")");
                }
            }
        });

        all_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAll = !isAll;
                all_select.setText(isAll ? "取消" : "全选");
                adapter.setAllSelect(isAll);
                selectList.clear();
                if (isAll)
                    selectList.addAll(userList);
                if ("0".equalsIgnoreCase(type)) {
                    count_member.setText("共计："+selectList.size());
                    menu.setText("下一步(" + selectList.size() + ")");
                } else {
                    count_member.setText("共计："+selectList.size());
                    menu.setText("完成(" + selectList.size() + ")");
                }
                adapter.notifyDataSetChanged();
            }
        });

        screen_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(MultiSelectActivity.this, ScreenUserActivity.class), 0x11);
            }
        });

        menu = (TextView) addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectList == null || selectList.size() == 0) {
                    showToast("请至少选择一个成员");
                    return;
                }

                if ("1".equalsIgnoreCase(type)) {
                    String seluserName = "";
                    String seluserId = "";

                    for (int i = 0; i < selectList.size(); i++) {
                        CrediterNewUser user = selectList.get(i);
                        if (user != null) {
                            seluserName = seluserName + user.getCreditorname() + ",";
                            if("sysuserid".equalsIgnoreCase(form)) {
                                seluserId = seluserId + user.getSysUserId() + ",";
                            }else{
                                seluserId = seluserId + user.getId() + ",";
                            }
                        }
                    }
                    Intent intent = new Intent(MultiSelectActivity.this, CreateProTalkActivity.class);
                    intent.putExtra("seluserName", seluserName);
                    intent.putExtra("seluserId", seluserId);
                    setResult(RESULT_OK, intent);
                    finish();
                    return;
                } else if ("2".equalsIgnoreCase(type)){
                    Intent intent = new Intent();
                    intent.putExtra("userList", (Serializable) selectList);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    Intent intent = new Intent(MultiSelectActivity.this, MultiSendActivity.class);
                    intent.putExtra("projectId", projectId);
                    intent.putExtra("userList", (Serializable) selectList);
                    startActivity(intent);
                    finish();
                }
            }
        }, "下一步", 0));
        if ("0".equalsIgnoreCase(type)) {
            menu.setText("下一步");
        } else {
            menu.setText("完成");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == RESULT_OK && data != null) {
            committee = data.getIntExtra("committee", 1);
            int online = data.getIntExtra("onlineStatus", 0);
            if (online == 0)
                onlineStatus = null;
            else if (online == 1)
                onlineStatus = true;
            else
                onlineStatus = false;

            kindTax = data.getBooleanExtra("kindTax", false);
            kindGuarantee = data.getBooleanExtra("kindGuarantee", false);
            kindOther = data.getBooleanExtra("kindOther", false);
            kindOrdinary = data.getBooleanExtra("kindOrdinary", false);
            minAmountDeclared = data.getDoubleExtra("minAmountDeclared", 0);
            maxAmountDeclared = data.getDoubleExtra("maxAmountDeclared", 0);
            minConfirmAmount = data.getDoubleExtra("minConfirmAmount", 0);
            maxConfirmAmount = data.getDoubleExtra("maxConfirmAmount", 0);
            processStatus = data.getStringExtra("processStatus");
            loadFirst();
        }
    }

    @Override
    public void loadFirst() {
        pageNo = 1;
        if (type.equals("2"))
            getCreditorList(true);
        else
            creditorListCnd(true);
    }

    @Override
    public void loadNext() {
        if (type.equals("2"))
            getCreditorList(false);
        else
            creditorListCnd(false);
    }

    /**
     * 获取成员
     */
    public void creditorListCnd(final boolean isFirst) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }
        Map<String, String> parms = new HashMap<>();
        parms.put("userToken", getUserToken());
        parms.put("projectId", projectId);
        parms.put("pageNumber", pageNo + "");
        parms.put("pageSize", pageSize + "");
        if (committee != null) parms.put("committee", committee + "");
        if (onlineStatus != null) parms.put("onlineStatus", onlineStatus + "");
        if (kindTax != null) parms.put("kindTax", kindTax + "");
        if (kindGuarantee != null) parms.put("kindGuarantee", kindGuarantee + "");
        if (kindOther != null) parms.put("kindOther", kindOther + "");
        if (kindOrdinary != null) parms.put("kindOrdinary", kindOrdinary + "");
        if (minAmountDeclared != null && minAmountDeclared != 0f) parms.put("minAmountDeclared", minAmountDeclared + "");
        if (maxAmountDeclared != null && maxAmountDeclared != 0f) parms.put("maxAmountDeclared", maxAmountDeclared + "");
        if (minConfirmAmount != null && minConfirmAmount != 0f) parms.put("minConfirmAmount", minConfirmAmount + "");
        if (maxConfirmAmount != null && maxConfirmAmount != 0f) parms.put("maxConfirmAmount", maxConfirmAmount + "");
        if (processStatus != null) parms.put("processStatus", processStatus + "");

        Network.getAPIService()
                .creditorListCnd(parms)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            showToast(json.get("msg").getAsString());
                            recyclerView.onFinishRequest(true, false);
                        } else {
                            if (isFirst) {
                                userList.clear();
                                selectList.clear();
                            }

                            JsonObject data = json.getAsJsonObject("data");
                            JsonObject jsonpagination = data.getAsJsonObject("pagination");
                            JsonArray array = jsonpagination.getAsJsonArray("list");
                            List<CrediterNewUser> temp = new ArrayList<>();

                            for (int i = 0;i < array.size();i++) {
                                CrediterNewUser item = new Gson().fromJson(array.get(i), CrediterNewUser.class);
                                if (selectIds.contains(item.getCreditorid())) {
                                    item.isCheck = true;
                                    selectList.add(item);
                                } else
                                    item.isCheck = false;
                                temp.add(item);
                            }

                            userList.addAll(temp);
                            try {
                                int count = data.get("totalCount").getAsInt();
                                recyclerView.onFinishRequest(false, pageNo * pageSize < count);
                            }catch (Exception ex)
                            {
                                recyclerView.onFinishRequest(false, true);
                            }
                            pageNo++;
                            if(isFirst) {
                                isAll = true;
                                all_select.setText(isAll ? "取消" : "全选");
                                adapter.setAllSelect(isAll);
                                selectIds.clear();
                                if (isAll) {
                                    for (CrediterNewUser idStr : userList) {
                                        selectIds.add(idStr.getId());
                                    }
                                }
                                menu.setText("完成(" + selectIds.size() + ")");
                                count_member.setText("共计："+selectIds.size());
                                selectList.addAll(userList);
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        recyclerView.onFinishRequest(true, false);
                    }
                });
    }

    /**
     * 获取成员
     */
    public void getCreditorList(final boolean isFirst) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        Map<String, String> parms = new HashMap<>();
        parms.put("userToken", getUserToken());
        parms.put("projectId", projectId);
        parms.put("pageNo", pageNo + "");
        parms.put("pageSize", pageSize + "");
        if (committee != null) parms.put("committee", committee + "");
        if (onlineStatus != null) parms.put("onlineStatus", onlineStatus + "");
        if (kindTax != null) parms.put("kindTax", kindTax + "");
        if (kindGuarantee != null) parms.put("kindGuarantee", kindGuarantee + "");
        if (kindOther != null) parms.put("kindOther", kindOther + "");
        if (kindOrdinary != null) parms.put("kindOrdinary", kindOrdinary + "");
        if (minAmountDeclared != null && minAmountDeclared != 0f) parms.put("minAmountDeclared", minAmountDeclared + "");
        if (maxAmountDeclared != null && maxAmountDeclared != 0f) parms.put("maxAmountDeclared", maxAmountDeclared + "");
        if (minConfirmAmount != null && minConfirmAmount != 0f) parms.put("minConfirmAmount", minConfirmAmount + "");
        if (maxConfirmAmount != null && maxConfirmAmount != 0f) parms.put("maxConfirmAmount", maxConfirmAmount + "");
        if (processStatus != null) parms.put("processStatus", processStatus + "");

        Network.getAPIService()
                .getCreditorList(parms)
//                .getCreditorList(getUserToken(), projectId, committee, onlineStatus,
//                        kindTax, kindGuarantee, kindOther, kindOrdinary, minAmountDeclared,
//                        maxAmountDeclared, minConfirmAmount, maxConfirmAmount, processStatus,
//                        orderBy, orderColumn, pageNo, pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(new Throwable(json.get("msg").getAsString()));
                            return;
                        } else {
                            if (isFirst) {
                                userList.clear();
                                selectList.clear();
                            }

                            JsonObject data = json.getAsJsonObject("data");
                            JsonArray array = data.getAsJsonArray("list");
                            List<CrediterNewUser> temp = new ArrayList<>();
                            for (int i = 0;i < array.size();i++) {
                                CrediterNewUser item = new Gson().fromJson(array.get(i), CrediterNewUser.class);
                                if (selectIds.contains(item.getCreditorid())) {
                                    item.isCheck = true;
                                    selectList.add(item);
                                } else
                                    item.isCheck = false;
                                temp.add(item);
                            }

                            userList.addAll(temp);
                            int count = data.get("totalCount").getAsInt();
                            recyclerView.onFinishRequest(false, pageNo * pageSize < count);
                            pageNo++;
                            if(isFirst) {
                                isAll = true;
                                all_select.setText(isAll ? "取消" : "全选");
                                adapter.setAllSelect(isAll);
                                selectIds.clear();
                                if (isAll) {
                                    for (CrediterNewUser idStr : userList) {
                                        selectIds.add(idStr.getId());
                                    }
                                }
                                menu.setText("完成(" + selectIds.size() + ")");

                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        recyclerView.onFinishRequest(true, false);
                    }
                });
    }
}
